package cloud.xiguapi.ubas.service.impl;

import cloud.xiguapi.ubas.analysis.uv.SetUVAnalysis;
import cloud.xiguapi.ubas.common.ApiResult;
import cloud.xiguapi.ubas.common.Pager;
import cloud.xiguapi.ubas.entity.SetUV;
import cloud.xiguapi.ubas.exceptions.ApiException;
import cloud.xiguapi.ubas.mapper.SetUVMapper;
import cloud.xiguapi.ubas.service.IUVService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * @author 大大大西西瓜皮🍉
 * date: 2021-5-20 下午 03:47
 * desc:
 */
@Service("setUVService")
@Slf4j
@Transactional(readOnly = true, rollbackFor = ApiException.class)
public class SetUVServiceImpl implements IUVService<SetUV> {

    private final SetUVMapper setUVMapper;

    private final SetUVAnalysis setUVAnalysis;

    @Autowired
    public SetUVServiceImpl(SetUVMapper setUVMapper, SetUVAnalysis setUVAnalysis) {
        this.setUVMapper = setUVMapper;
        this.setUVAnalysis = setUVAnalysis;
    }

    @Override
    public ApiResult<Pager<SetUV>> selectPage(long current, long size) {
        log.info("基于集合的UV统计查询, 参数： current = {}, size = {}", current, size);
        IPage<SetUV> page = setUVMapper.selectPage(new Page<>(current, size));
        return ApiResult.success(Pager.<SetUV>builder()
                .current(page.getCurrent())
                .size(page.getSize())
                .total(page.getTotal())
                .records(page.getRecords())
                .build());
    }

    @Override
    public ApiResult<Object> analysis(String path) {
        log.info("基于集合的UV统计分析, 参数: path = {}", path);
        try {
            setUVAnalysis.analysis(path);
            return ApiResult.success(Optional.empty(), "基于集合的UV统计分析完成");
        } catch (Exception e) {
            log.error("基于集合的UV分析失败, 原因:\n {}", e.getMessage());
            return ApiResult.failed("基于集合的UV统计分析失败");
        }
    }
}
